<template>
  <div class="After-loan" :class="{'bg': borrowAfterState.overdueDays }">
    <div style="position: relative;width:100%;height:50px;">
      <van-nav-bar
        title="待还账单"
        fixed
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <div class="header">
      <!-- 未逾期 -->
      <div v-if="borrowAfterState.overdueDays==0">
        <p class="text1">{{borrowAfterState.number}}/{{borrowAfterState.totalNumber}}期应还款</p>
        <p class="text2">¥{{(repayPlans.repayMoney/100).toFixed(2)}} <van-icon class="question" size="18px"  color="#FF8024" name="question" @click="detailDialog(0)"/></p>
        <p class="text3" >应还款日：{{repayPlans.repayDate}}</p>
      </div>
      <!-- 已逾期 -->
      <div v-if="borrowAfterState.overdueDays!=0">
        <p class="text1">逾期未还总额</p>
        <p class="text2">¥{{(borrowAfterState.totalRepayMoney/100).toFixed(2)}}</p>
        <p class="text3">逾期 <span style="color:#E72427">{{borrowAfterState.overdueDays}}天</span>，请立即还款</p>
      </div>
    </div>
    <div v-if="borrowAfterState.overdueDays==0">
      <div class="box">
        <p class="text-left error-msg" v-if="AutoHintState">
          <van-icon slot="icon" class="info-icon" class-prefix="my-icon" size="14px"  color="#FF4251" name="info" />
          {{AutoHint}}
        </p>
        <van-cell-group class="list">
          <van-cell class="text-left" title="还款计划" value="还款日将自动扣款"  is-link @click="repaymentDetail"/>
          <van-cell class="text-left" title="还款账户" :value="bankCardDto.sortName"  is-link   @click="setBankCardClick"/>
        </van-cell-group>
      </div>
      <!-- <div class="Settlement-of text-right">一次性结清</div> -->
      <div class="repaymentBtn" @click="repaymentClick"  v-if="BtnShow">立 即 还 款</div>
      <div class="text-left hint">
        <p>温馨提示：</p>
        <p>1、还款日系统将自动批扣，批扣时间为8点30分、15点30分、20点30分左右，,批扣期间无法主动还款，避免批扣两次~</p>
        <p>2、批扣失败，可以选择主动还款，以免逾期</p>
        <p>3、还款若遇到其它问题，可以联系客服：4009961777</p>
      </div>
    </div>
    <div class="overdue" v-if="borrowAfterState.overdueDays!=0">
      <van-cell-group>
      <van-cell class="account text-left" title="还款账户" :value="bankCardDto.sortName" />
      </van-cell-group>
      <p class="text-left error-msg" v-if="AutoHintState">
        <van-icon slot="icon" class="info-icon" class-prefix="my-icon" size="14px"  color="#FF4251" name="info" />
        {{AutoHint}}
      </p>
      <div class="overdue-list">
        <div class="overdue-item" v-for="(item,index) in borrowAfterState.repayPlans" :key="index">
          <div class="overdue-header">
            <div><i class="title-icon"></i>第{{item.number}}期<span class="overdue-btn" v-if="item.overdueDays>0">已逾期</span></div>
            <div class="reimbursement" :class="{'disable':index!=0}" v-if="item.state!=30" @click="repaymentClick">立即还款</div>
            <div style="color:#E72427" v-if="item.state==30">系统扣款中</div>
          </div>
          <div class="main">
            <div class="main-left text-left">
              <p class="main-tit">应还款日</p>
              <p class="main-con">{{item.repayDate}}</p>
            </div>
            <div class="main-right text-left">
              <p class="main-tit">应还金额(元)</p>
              <p class="main-con">{{(item.repayMoney/100).toFixed(2)}} <van-icon color="#FF8024" class="money-icon" size="14px" class-prefix="my-icon" name="info" @click="detailDialog(index)"/></p>
            </div>
          </div>
        </div>

      </div>
    </div>
    <van-actionsheet v-model="planShow" title="还款计划">
      <div class="plan-box">
        <p class="plan-hine">温馨提示：还款计划仅显示剩余应还账单，已还款账单不展示</p>
        <van-cell-group>
            <div class="plan-year text-left" v-if="arr1.length>0">{{arr[0].repayYear}}年</div>
            <van-cell class="text-left" value-class="text-right" :title="`第${item.number}期 ${(item.repayDate)}`" :value="`¥${(item.repayMoney/100).toFixed(2)}`" v-for="(item,index) in arr" :key="index" />
            <div class="plan-year text-left" v-if="arr1.length>0">{{arr1[0].repayYear}}年</div>
            <van-cell class="text-left" value-class="text-right" title="第1期  12月09日" value="¥158.35"  v-for="(item,index) in arr1" :key="index">

            </van-cell>
        </van-cell-group>
      </div>
    </van-actionsheet>
  </div>
</template>

<script>
import {Icon, Cell, CellGroup ,Panel, Dialog, Actionsheet, Toast,NavBar } from 'vant';
var  timer=0;
export default {
  components:{
    [Icon.name]:Icon,
    [Cell.name]:Cell,
    [CellGroup.name]:CellGroup,
    [Panel.name]:Panel,
    [Dialog.name]:Dialog,
    [Actionsheet.name]:Actionsheet,
    [Toast.name]:Toast,
    [NavBar.name]:NavBar,
  },
  //
  data(){
    return{
      overdue:false,
      planShow:false,
      token:'',
      info:'',
      borrowAfterState:'',//当前进度信息
      repayPlans:'',//本期还款计划
      bankCardDto:'',
      arr:[],//不跨年计划
      arr1:[],//跨年计划
      disabled:false,
      AutoHint:'',
      AutoHintState:false,
      BtnShow:true,
    }
  },
  destroyed(){
    if(timer) { //如果定时器在运行则关闭
        clearInterval(timer);
    }
  },
  mounted(){
    _hmt.push(['_trackPageview', '/After-the-loan']);
    this.$util.goBack();
    Toast.loading({duration:1000,mask: false,message: '加载中...'});
    let _this = this;
    this.$util.getUser().then(token=>{
      console.log(token)
       this.token=token;
      if(token!='-1'){
        _this.myInfo(token);
        _this.borrowAfterSchedule()
      }
    })
  },
  methods:{
    onClickLeft(){
      this.$util.url('/homeAfter','首页')
    },
    setBankCardClick(){
      Toast('暂不支持修改银行卡')
    },
    // 进度查询
    borrowAfterSchedule(noloading){
      if(!noloading){
        Toast.loading({message: '进度查询...'});
      }
      let _this = this;
      clearInterval(timer)
      this.$api.get('/borrowAfter/v1/borrowAfterSchedule?bankrollCode='+this.$util.bankrollCode,{},s=>{
        console.log(s)
        Toast.clear()
        //还清逻辑
        if(s.module.totalRepayMoney==0){
          _this.$util.url('/HomeBefore','首页')
          return false;
        }
        _this.state = s.module.state;

        //初始化页面
        // let state = s.module.state;
        _this.borrowAfterState = s.module;
        // alert(JSON.stringify(s.module))
        let repayPlans = s.module.repayPlans[0];//还款计划
        repayPlans.repayDate = repayPlans.repayDate.split(" ")[0]
        console.log(repayPlans)
        _this.repayPlans = repayPlans;//当前计划
        _this.bankCardDto = s.module.bankCardDto;//卡
        //所以计划
        let repayPlansList = s.module.repayPlans;
        let year = new Date().getFullYear();
        let arr =[];// 应还款年份相同
        let arr1 = [];//应还款年不份同
        //数据结构
        for(var i=0;i<repayPlansList.length;i++){
          repayPlansList[i].repayDate = repayPlansList[i].repayDate.split(" ")[0]
          if(repayPlansList[i].repayYear == year ){
            arr.push(repayPlansList[i])
          }else{
            arr1.push(repayPlansList[i])
          }
        }
          _this.arr = arr;
          _this.arr1 = arr1;
          _this.BtnShow =true;
          // alert(repayPlans.state);
        if(repayPlans.state == 1||repayPlans.state == 30){
          //正在扣款
          _this.AutoHintState =true;
          _this.AutoHint = `系统正在扣款中，请确保您的银行卡余额充足。`
          _this.BtnShow =false;
          // 审核中定时刷新页面更新状态
          timer=setInterval(() => {
            _this.borrowAfterSchedule('noloading');
          }, 5000)
        }else if(repayPlans.state == 40){
          //扣款失败
          _this.AutoHintState =true;
          _this.AutoHint = `系统扣款失败，可能原因：1.卡异常或余额不足；2.未开通无卡支付；3.卡日限额被限制；4.其它原因`
        }
      },f=>{
        if(f.resultCode=='10000'||f.resultCode=='10003'||f.resultCode=='10001'||f.resultCode=='10002'){
          _this.$util.url('/HomeBefore','首页')
        }else{
          Toast(f.errorMessage);
        }
      },{
        'Accept': 'application/json',
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':this.token
      })
    },
    // 本期应还
    detailDialog(index){

      let dom = `<div class="detail">
        <div>第${this.borrowAfterState.repayPlans[index].number}/${this.borrowAfterState.totalNumber}期<div>
        <div class="space-between"><span>应还本金</span><span>¥${(this.borrowAfterState.repayPlans[index].principal/100).toFixed(2)}</span></div>
        <div class="space-between"><span>当前利息</span><span>¥${(this.borrowAfterState.repayPlans[index].interest/100).toFixed(2)}</span></div>
        <div class="space-between"><span>逾期罚息</span><span>¥${(this.borrowAfterState.repayPlans[index].overdueFee/100).toFixed(2)}</span></div>
        <div class="space-between"><span>合计</span><span>¥${(this.borrowAfterState.repayPlans[index].repayMoney/100).toFixed(2)}</span></div>
      </div>`

      Dialog.alert({
        title: '还款明细',
        message: dom,
        confirmButtonText:'我知道了'
      }).then(() => {
        // on close
      });
    },
    // 还款
    repaymentClick(){
      Dialog.confirm({
        title: '温馨提示',
        message: '是否确认还款？'
      }).then(() => {
        console.log(123)
        this.repayment();
        // on confirm
      }).catch(() => {
        console.log(456)
        // on cancel
      });
    },
    repayment(){
      Toast.loading({message: '还款中...'});
      let _this = this;
      this.$api.post('/borrowAfter/v1/repayment?bankrollCode='+this.$util.bankrollCode,{},s=>{
        console.log(s);
        if(s.module){
          // Toast('还款成功');
            Toast.clear()
          // _this.$util.url('/HomeAfter','首页');
           _this.borrowAfterSchedule()
        }else{
          Toast('还款失败，请重试！');
        }

      },f=>{
        if(f.resultCode=='10000'||f.resultCode=='10003'||f.resultCode=='10001'||f.resultCode=='10002'){
          _this.$util.url('/HomeBefore','首页')
        }else{
          Toast(f.errorMessage);
        }
      },{
        'Accept': 'application/json',
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':this.token
      })
    },
    // 还款计划
    repaymentDetail(){
      this.planShow=true;
    },
    myInfo(token){
      let _this = this;
      this.$api.post('/user/v1/info',{},s=>{
        console.log(s);
        _this.info = s.module;

      },f=>{
        if(f.resultCode=='10000'||f.resultCode=='10003'||f.resultCode=='10001'||f.resultCode=='10002'){
          _this.$util.url('/HomeBefore','首页')
        }else{
          Toast(f.errorMessage);
        }
      },{
        'Accept': 'application/json',
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':token
      })
    }
  }
}
</script>
<style>
.space-between{
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  line-height: 30px;
  color:#41424E;
}
.van-cell__value.text-center{
  text-align: center;
}
</style>

<style scoped lang="scss">
  /***
  * 产品主题颜色需求
  * #FF8024 按钮 突出文字 ico
  * #FFD500 B辅助色
  * #FFEC9C c辅助色
  * #1D0F00 重要文字
  * #41424E 副标题段落
  * #797A79 次要文字
  * #A9AAA9 不可点击
  * #E6E6E6 分割线 描边
  * #F6F7F6 背景
  * #6699CC 链接
  */
.After-loan{
  width: 100%;
  height:100%;
  background: #fff;
}
.bg{
  background:#F6F7F6;
}
.header{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height:170px;
  background: #fff;
  .text1{
    margin-top:20px;
    font-size:14px;
    line-height:20px;
    color:#41424E;
  }
  .text2{
    margin-top:4px;
    font-size:40px;
    line-height:42px;
    color:#1D0F00;
  }
  .text3{
    margin-top:20px;
    font-size:14px;
    line-height:20px;
    color:#797A79;
  }
}

.box{
  overflow: hidden;
  width:90%;
  margin:15px auto 0;
  border-radius: 10px;
  box-shadow: 0 3px 9px 3px rgba(0,0,0,0.05);
}
.question{
  position: relative;
  top:-13px
}
.Settlement-of{
  padding-right:5%;
  margin-top:16px;
  font-size:14px;
  line-height:20px;
  color:#FF8024;
}
.hint{
  padding:0 5%;
  margin-top:16px;
  font-size:12px;
  color:#999;
}
.error-msg{
  padding:10px;
  font-size:12px;
  color:#FF4251;
}
.info-icon{
  position: relative;
  top:2px;
}
.repaymentBtn{
  width:80%;
  height:40px;
  margin:30px auto 0;
  text-align: center;
  font-size:14px;
  line-height: 40px;
  background: #FF8024;
  border-radius: 8px;
  color:#fff;
}
.account{
  margin-top:8px;
}
.overdue-list{
  margin-top:10px;
}
.overdue-item{
  height:128px;
  margin-bottom:10px;
  background:#fff;
  .overdue-header{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    width:90%;
    height:48px;
    margin:0 auto;
    font-size:14px;
    line-height: 48px;
    border-bottom:1px solid #E6E6E6;
  }
  .title-icon{
    display:inline-block;
    width:4px;
    height:12px;
    margin-right:4px;
    border-radius: 2px;
    background: #E72427;
  }
  .overdue-btn{
    padding:2px 5px;
    margin-left:4px;
    font-size:12px;
    border-radius: 5px;
    border:1px solid #E72427;
    color:#E72427;
  }
  .reimbursement{
    // height:34px;
    height:30px;
    width:80px;
    margin-top:9px;
    line-height: 30px;
    border-radius: 20px;
    font-size:12px;
    color:#E72427;
    border:1px solid #E72427;
    &.disable{
      pointer-events: none;
      // background: #797A79;
      color:#797A79;
      border:1px solid #797A79;
    }
  }
  .main{
    display: flex;
    flex-direction: row;
  }
  .main-left,.main-right{
    flex:1;
    padding-left:16px;
    .main-tit{
      margin-top:16px;
      font-size:12px;
      line-height: 20px;
      color:#797A79;
    }
    .main-con{
      margin-top:6px;
      font-size:20px;
      // font-weight: 600;
      line-height: 28px;
      color:#1D0F00;

    }
    .money-icon{
      position: relative;
      top:-5px;
    }
  }
}
.plan-box{
  .plan-hine{
    font-size:12px;
    color:#797A79;
  }
}
.plan-year{
  margin-left:16px;
  padding-top:16px;
  font-size:16px;
  font-weight:600;
}

</style>